<template>
  <div class="source-edit-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-slate-800 ">编辑新闻源</h1>
        </div>
        <div class="flex space-x-3">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="danger" @click="handleDeleteClick" :loading="deleting">删除</el-button>
          <el-button type="primary" @click="handleSaveClick" :loading="saving">保存</el-button>
        </div>
      </div>
    </div>

    <!-- 新闻源表单 -->
    <SourceForm
      ref="sourceFormRef"
      mode="edit"
      :source-id="sourceId"
      :initial-data="sourceData"
      @save="handleSave"
      @delete="handleDelete"
      @cancel="handleCancel"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { sourceAPI } from '~/services/api'
import SourceForm from '~/components/admin/SourceForm.vue'

// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

const router = useRouter()
const route = useRoute()
const sourceFormRef = ref()
const saving = ref(false)
const deleting = ref(false)

// 新闻源ID
const sourceId = route.params.id

// 新闻源数据
const sourceData = ref({})

// 加载新闻源详情
const loadSourceDetail = async () => {
  try {
    const result = await sourceAPI.getSourceById(sourceId)
    
    if (result.code === 200) {
      sourceData.value = result.data
    } else {
      ElMessage.error(result.message || '加载新闻源详情失败')
      router.push('/admin/source/list')
    }
  } catch (error) {
    console.error('加载新闻源详情失败:', error)
    ElMessage.error('加载新闻源详情失败')
    router.push('/admin/source/list')
  }
}

// 保存新闻源（表单组件调用）
const handleSave = async (formData) => {
  try {
    saving.value = true
    
    // 调用后端API更新新闻源
    const result = await sourceAPI.updateSource(formData)
    
    if (result.code === 200) {
      ElMessage.success('更新新闻源成功')
      router.push('/admin/source/list')
    } else {
      ElMessage.error(result.message || '更新新闻源失败')
    }
  } catch (error) {
    console.error('更新新闻源失败:', error)
    ElMessage.error('更新新闻源失败，请重试')
  } finally {
    saving.value = false
  }
}

// 删除新闻源（表单组件调用）
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除「${sourceData.value.name}」新闻源吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    deleting.value = true
    
    // 调用后端API删除新闻源
    const result = await sourceAPI.deleteSource(id)
    
    if (result.code === 200) {
      ElMessage.success('删除新闻源成功')
      router.push('/admin/source/list')
    } else {
      ElMessage.error(result.message || '删除新闻源失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除新闻源失败:', error)
      ElMessage.error('删除新闻源失败，请重试')
    }
  } finally {
    deleting.value = false
  }
}

// 保存按钮点击事件
const handleSaveClick = () => {
  sourceFormRef.value?.handleSave()
}

// 删除按钮点击事件
const handleDeleteClick = () => {
  sourceFormRef.value?.handleDelete()
}

// 取消操作
const handleCancel = () => {
  router.push('/admin/source/list')
}

// 组件初始化
onMounted(() => {
  loadSourceDetail()
})
</script>

<style scoped>
.source-edit-page {
  @apply w-full;
}
</style>
